package com.mianyang.zhangsan.common.util;


import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileNotFoundException;


@Slf4j
public class VideoUtils {

    public static long getVideoDuration(MultipartFile file) {
        long duration = 0;
        try {
            File source = new File(getFilePath() + file.getOriginalFilename());
            file.transferTo(source);
            return getVideoDuration(source);
        } catch (Exception e) {
            log.error("时长计算失败-{}", e.getMessage());
            return duration;
        }
    }

    public static long getVideoDuration(File file) {
        long duration = 0;
        try {
            Encoder encoder = new Encoder();
            MultimediaInfo info = encoder.getInfo(file);
            duration = info.getDuration();
            if (file.exists()) {
                file.delete();
            }
            return duration;
        } catch (EncoderException e) {
            return duration;
        }
    }

    public static String getFilePath() {
        //获取当前文件的根路径
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (!path.exists()) path = new File("");

        //盘符路径
        StringBuilder codeUrl = new StringBuilder();
        codeUrl.append(path.getAbsolutePath()).append("\\static\\video\\");
        File file = new File(codeUrl.toString());
        if (!file.exists()) {
            file.mkdirs();
        }
        return codeUrl.toString();
    }
}
